package com.qdsg.ysg.doctor.pharmacist.fragment;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.graphics.Canvas;
import android.graphics.Rect;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.annotation.Nullable;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.qdsg.ysg.doctor.R;
import com.qdsg.ysg.doctor.base.BaseApplication;
import com.qdsg.ysg.doctor.base.BaseFragment;
import com.qdsg.ysg.doctor.pharmacist.activity.CheckActivity;
import com.qdsg.ysg.doctor.pharmacist.activity.PrescriptionCheckedActivity;
import com.qdsg.ysg.doctor.ui.activity.mine.SignatureActivity;
import com.qdsg.ysg.doctor.ui.activity.mine.SignatureSettingActivity;
import com.qdsg.ysg.doctor.ui.dialog.SignatureDialog;
import com.qdsg.ysg.doctor.util.DpUtil;
import com.qdsg.ysg.doctor.util.ImageLoaderHelper;
import com.qdsg.ysg.doctor.util.ToastUtil;
import com.rest.business.RestProxy;
import com.rest.exception.BusinessException;
import com.rest.response.AuthOauthVo;
import com.rest.response.CheckResponse;
import com.rest.response.OauthStatusResponse;
import com.rest.response.UserInfoBean;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.constant.SpinnerStyle;
import com.scwang.smartrefresh.layout.footer.BallPulseFooter;
import com.scwang.smartrefresh.layout.header.ClassicsHeader;

import org.jetbrains.annotations.NotNull;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

import butterknife.BindView;
import butterknife.OnClick;
import io.reactivex.Observer;
import io.reactivex.disposables.Disposable;

/**
 * 处方审核列表
 *
 * @time 2020/12/1 17:22
 */

public class PrescriptionFragment extends BaseFragment {

    @BindView(R.id.refreshLayout)
    RefreshLayout refreshLayout;
    @BindView(R.id.recyclerView)
    RecyclerView recyclerView;


    private MyAdapter adapter;

    private List<CheckResponse.Check> list = new ArrayList<>();


    @SuppressLint("StaticFieldLeak")
    private static PrescriptionFragment prescriptionFragment;

    public static PrescriptionFragment newInstance() {
        if (prescriptionFragment == null) {
            prescriptionFragment = new PrescriptionFragment();
            return prescriptionFragment;
        } else {
            return prescriptionFragment;
        }
    }

    public static void Logout() {
        prescriptionFragment = null;
    }

    @Override
    protected int getLayoutResource() {
        return R.layout.fragment_prescription;
    }

    @Override
    protected void initView() {
        LinearLayoutManager manager = new LinearLayoutManager(getActivity());
        manager.setOrientation(LinearLayoutManager.VERTICAL);
        recyclerView.setLayoutManager(manager);
        adapter = new MyAdapter();
        recyclerView.setAdapter(adapter);
        recyclerView.addItemDecoration(new RecyclerView.ItemDecoration() {
            @Override
            public void onDraw(@NotNull Canvas c, @NotNull RecyclerView parent, @NotNull RecyclerView.State state) {
                super.onDraw(c, parent, state);
            }

            @Override
            public void getItemOffsets(@NotNull Rect outRect, @NotNull View view, @NotNull RecyclerView parent, @NotNull RecyclerView.State state) {
                super.getItemOffsets(outRect, view, parent, state);
                outRect.bottom = DpUtil.dip2px(mContext, 1);
            }
        });

        refreshLayout.setEnableLoadMore(false);
        refreshLayout.setOnRefreshListener(refreshlayout -> initData());
        refreshLayout.setOnLoadMoreListener(refreshlayout -> initData());
    }

    @Override
    protected void initData() {
        getCheckList();
    }

    @OnClick(R.id.btn_checked)
    void btn_checked() {
        startActivity(PrescriptionCheckedActivity.class);
    }

    class MyAdapter extends RecyclerView.Adapter<MyAdapter.Holder> {

        @NotNull
        @Override
        public MyAdapter.Holder onCreateViewHolder(@NotNull ViewGroup parent, int viewType) {
            MyAdapter.Holder myHolder;
            myHolder = new MyAdapter.Holder(LayoutInflater.from(getActivity()).inflate(R.layout.item_im, parent, false));
            return myHolder;
        }

        @SuppressLint("SetTextI18n")
        @Override
        public void onBindViewHolder(MyAdapter.Holder holder, final int position) {
            holder.itemView.setOnClickListener(v -> {
                querySignStatus(position);
            });
            holder.tv_name.setText(list.get(position).strType + "处方");
            holder.tv_department.setVisibility(View.GONE);
            holder.tv_message.setText(list.get(position).docName);
            holder.tv_time.setText(list.get(position).createTime);
//            if(list.get(position).unreadCount!=0){
//                holder.tv_unreadCount.setVisibility(View.VISIBLE);
//                holder.tv_unreadCount.setText(list.get(position).unreadCount+"");
//            }else {
            holder.tv_unreadCount.setVisibility(View.GONE);
//            }
            ImageLoaderHelper.getInstance().GlideImageLoader(mContext, list.get(position).url, holder.img_head, R.mipmap.img_default);
        }

        @Override
        public int getItemCount() {
            return list.size();
        }

        class Holder extends RecyclerView.ViewHolder {

            TextView tv_name, tv_department, tv_message, tv_time, tv_unreadCount;
            ImageView img_head;

            Holder(View itemView) {
                super(itemView);
                tv_name = itemView.findViewById(R.id.tv_name);
                tv_unreadCount = itemView.findViewById(R.id.tv_unreadCount);
                tv_time = itemView.findViewById(R.id.tv_time);
                tv_department = itemView.findViewById(R.id.tv_department);
                tv_message = itemView.findViewById(R.id.tv_message);
                img_head = itemView.findViewById(R.id.img_head);
            }
        }
    }

    @Override
    public void onResume() {
        super.onResume();
        initData();
    }

    //查询是否已实名认证和签名
    public void querySignStatus(int position) {
        RestProxy.getInstance().querySignStatus(BaseApplication.currentUserId, new Observer<UserInfoBean>() {
            @Override
            public void onSubscribe(Disposable d) {

            }

            @Override
            public void onNext(UserInfoBean userInfoBean) {
                //realNameStatus为0 表示已实名认证  signatureImg不为空表示已签名
                if ("0".equals(userInfoBean.data.realNameStatus) && !TextUtils.isEmpty(userInfoBean.data.signatureImg)) {
                    queryOauthStatus(position);
                } else {
                    SignatureDialog mSignatureDialog = SignatureDialog.newInstance();
                    mSignatureDialog.setmListener(new SignatureDialog.OnItemClickListener() {
                        @Override
                        public void onConfirm() {
                            startActivity(SignatureSettingActivity.class);
                        }

                        @Override
                        public void onCancel() {
                        }
                    });
                    mSignatureDialog.show(getChildFragmentManager(), "mSignatureDialog");
                }
            }


            @Override
            public void onError(Throwable e) {
                ToastUtil.onError(mContext, e);
            }

            @Override
            public void onComplete() {

            }
        });
    }


    /**
     * 查询授权状态接口
     */
    public void queryOauthStatus(int position) {
        RestProxy.getInstance().queryOauthStatus(new Observer<OauthStatusResponse>() {
            @Override
            public void onSubscribe(Disposable d) {

            }

            @Override
            public void onNext(OauthStatusResponse oauthStatusResponse) {
                Bundle bundle = new Bundle();
                bundle.putSerializable("obj", list.get(position));
                startActivity(CheckActivity.class, bundle);
            }

            @Override
            public void onError(Throwable e) {
                if (e instanceof BusinessException) {
                    if (((BusinessException) e).errorCode == 2300) {
                        authOauth();
                    } else {
                        ToastUtil.onError(mContext, e);
                    }
                }
            }

            @Override
            public void onComplete() {
            }
        });
    }

    /**
     * 授权接口
     */
    public void authOauth() {
        RestProxy.getInstance().authOauth(new Observer<AuthOauthVo>() {
            @Override
            public void onSubscribe(Disposable d) {

            }

            @Override
            public void onNext(AuthOauthVo authOauthVo) {
                Bundle bundle = new Bundle();
                bundle.putString("url", authOauthVo.data.oauthURL);
                bundle.putInt("type", 1);
                startActivity(SignatureActivity.class, bundle);
            }

            @Override
            public void onError(Throwable e) {

            }

            @Override
            public void onComplete() {
            }
        });

    }

    private void getCheckList() {
        RestProxy.getInstance().getCheckList("0", "", new Observer<CheckResponse>() {
            @Override
            public void onSubscribe(Disposable d) {

            }

            @Override
            public void onNext(CheckResponse checkResponse) {
                list.clear();
                list.addAll(checkResponse.data.records);
                adapter.notifyDataSetChanged();
            }

            @Override
            public void onError(Throwable e) {
                ToastUtil.onError(mContext, e);
                refreshLayout.finishRefresh(false);
            }

            @Override
            public void onComplete() {
                refreshLayout.finishRefresh(true);
            }
        });
    }
}
